import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInFo } from '@/api/user'
const state = {
  token: getToken(),
  userInFo: {}// 初始化用户信息
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken() {
    state.token = null
    removeToken()
  },
  setUserInFo(state, userInFo) {
    state.userInFo = userInFo
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  async getUserInFo(context) {
    const res = await getUserInFo()
    context.commit('setUserInFo', res)
  },
  logout(context) {
    context.commit('removeToken') // 移除token
    context.commit('setUserInFo', {}) // 将用户信息也设为空对象
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
